package com.yunbiao.ybbusstopplate.refactoring.serial;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ServiceUtils;
import com.yunbiao.ybbusstopplate.refactoring.utils.L;
import com.yunbiao.ybbusstopplate.refactoring.Config;
import com.yunbiao.ybbusstopplate.refactoring.agreement.base.Parser;
import com.yunbiao.ybbusstopplate.refactoring.utils.Utils;
import com.yunbiao.ybbusstopplate.utils.BytesUtils;

import java.io.IOException;
import java.security.InvalidParameterException;

import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;

public class SerialPortServices extends Service {
    private static final String TAG = "SerialPortServices";

    public static void start(){
        stop();
        ServiceUtils.startService(SerialPortServices.class);
    }

    public static void stop(){
        if(ServiceUtils.isServiceRunning(SerialPortServices.class)){
            ServiceUtils.stopService(SerialPortServices.class);
        }
    }

    private Config.Agreement agreement;
    private SerialHelper serialHelper;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        openSerialPort();
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(serialHelper != null){
            try {
                if(serialHelper.isOpen()){
                    serialHelper.close();
                }
            } catch (Exception e){
                L.e(TAG,"关闭串口异常",e);
            }
            serialHelper = null;
        }
    }

    private void openSerialPort(){
        agreement = Config.getAgreement();
        if(agreement == null){
            L.d(TAG,"未配置协议");
            return;
        }
        L.d(TAG,String.format("当前协议:%1$s, 波特率:%2$s",agreement.getName(),agreement.getBaudRate()));

        try {
            agreement.initParser();
            Parser parser = agreement.getParser();
            Log.d(TAG, "openSerialPort: " + parser);
            if(parser != null){
                parser.loadCache();
            }
        } catch (Exception e) {
            L.e(TAG,"初始化解析器失败",e);
            return;
        }

        serialHelper = new SerialHelper(Config.PORT,agreement.getBaudRate()){
            @Override
            public void open() throws SecurityException, IOException, InvalidParameterException {
                try {
                    super.open();
                } catch (Exception e){

                }
                L.d(TAG,String.format("%1$s 串口%2$s", Config.PORT, isOpen() ? "已启动" : "未启动"));
            }

            @Override
            public void close() {
                super.close();
                L.d(TAG,String.format("%1$s 串口已关闭",Config.PORT));
            }

            @Override
            protected void onDataReceived(ComBean comBean) {
                if(comBean != null && comBean.bRec != null && comBean.bRec.length > 0){
                    try {
                        String hex = BytesUtils.bytesToHex(comBean.bRec);
                        L.d(TAG, String.format("<---%1$s",hex));
                        Parser parser = agreement.getParser();
                        if(parser != null){
                            parser.analyzing(serialHelper,comBean);
                        } else {
                            L.e(TAG,"未配置解析器");
                        }
                    } catch (Throwable e) {
                        L.e(TAG,"解析异常",e);
                    }
                } else {
                    L.e(TAG,"数据为NULL");
                }
            }

            @Override
            public void sendHex(String sHex) {
                super.sendHex(sHex);
                L.d(TAG, String.format("--->%1$s",sHex));
            }
        };
        serialHelper.setStickPackageHelper(inputStream -> {
            byte[] bytes = new byte[512];
            try {
                int size = inputStream.read(bytes);
                if(size > 0){
                    return Utils.subBytes(bytes,0,size);
                }
            } catch (IOException e){
                L.e(TAG,e);
            }
            return bytes;
        });
//        serialHelper.setStickPackageHelper(inputStream -> {
//            try {
//                int available = inputStream.available();
//                if (available > 0) {
//                    byte[] buffer = new byte[available];
//                    int size = inputStream.read(buffer);
//                    if (size > 0) {
//                        return buffer;
//                    }
//                } else {
//                    SystemClock.sleep(50);
//                }
//            } catch (IOException e) {
//                L.e(TAG,e);
//            }
//            return null;
//        });
        try {
            serialHelper.open();
        } catch (IOException e) {
            L.e(TAG,"串口启动异常",e);
        }
    }

}
